package com.sk.cardeal.act.recommend;

import android.os.Bundle;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import com.sk.cardeal.R;
import com.sk.cardeal.base.BaseActivity;
import com.sk.cardeal.view.TitleView;

import org.w3c.dom.Document;
import org.w3c.dom.Element;

import butterknife.BindView;

/**
 * Created by sk on 2018/4/25.
 */

public class ArticleDetailsActivity extends BaseActivity {
    @BindView(R.id.webView)
    WebView webView;
    @BindView(R.id.title_view)
    TitleView titleView;

    private String data;
    private String title;

    @Override
    protected int getContentView() {
        return R.layout.activity_article_details;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        titleView.setMyCallBack(this);
        titleView.setTitle(title);
        title = getIntent().getStringExtra("title");
        data = getIntent().getStringExtra("data");
        titleView.setTitle(title);
        WebSettings webSettings = webView.getSettings();//获取webview设置属性
        webSettings.setJavaScriptEnabled(true);//支持js
        String str =  "<HTML><Div align=\"center\" "+data+"</Div>";
        webView.loadDataWithBaseURL(null, str, "text/html", "UTF-8", null);
        webView.setWebViewClient(new MyWebViewClient());
    }

    @Override
    public void clickTitle(int i) {
        super.clickTitle(i);
        switch (i){
            case 1:
                finish();
                break;
        }
    }

    private class MyWebViewClient extends WebViewClient {

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            imgReset();//重置webview中img标签的图片大小
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            view.loadUrl(url);
            return true;
        }
    }

    /**
     * 对图片进行重置大小，宽度就是手机屏幕宽度，高度根据宽度比便自动缩放
     **/
    private void imgReset() {
        webView.loadUrl("javascript:(function(){" +
                "var objs = document.getElementsByTagName('img'); " +
                "for(var i=0;i<objs.length;i++)  " +
                "{"
                + "var img = objs[i];   " +
                "    img.style.maxWidth = '100%'; img.style.height = 'auto'; " +
                "}" +
                "})()");
    }
}
